<template>
  <p-modal v-model="visible" :width="1230" :mask-closable="false" title="产品BOM物料分配" @cancel="onCancel" @ok="onOk">
    <!--头部信息-->
    <div>
      <p-form :label-col="{span: 6}" :wrapper-col="{span: 18}">
        <p-row>
          <p-col :xl="8">
            <p-form-item label="产品编码" label-align="right">
              <p-input :value="model.productCode" disabled />
            </p-form-item>
          </p-col>
          <p-col :xl="8">
            <p-form-item label="产品名称" label-align="right">
              <p-input :value="model.productName" disabled />
            </p-form-item>
          </p-col>
          <p-col :xl="8">
            <p-form-item label="产品规格" label-align="right">
              <p-input :value="model.productSeries" disabled />
            </p-form-item>
          </p-col>
          <p-col :xl="8">
            <p-form-item label="工艺路线编码" label-align="right">
              <p-input :value="model.routeCode" disabled />
            </p-form-item>
          </p-col>
          <p-col :xl="8">
            <p-form-item label="版本号" label-align="right">
              <p-input :value="model.version" disabled />
            </p-form-item>
          </p-col>
          <p-col :xl="8">
            <p-form-item label="物料编码">
              <p-input v-model.trim="params.mcode" />
            </p-form-item>
          </p-col>
          <p-col :xl="8">
            <p-form-item label="工站编码">
              <p-input v-model.trim="params.workstationCode" />
            </p-form-item>
          </p-col>
          <p-col :xl="8">
            <p-form-item label="管控类型">
              <p-select v-model="params.maintenanceSap" allow-clear>
                <p-select-option value="1">SN管控</p-select-option>
                <p-select-option value="2">PN管控</p-select-option>
              </p-select>
            </p-form-item>
          </p-col>
          <p-col :xl="8">
            <div style="padding-left: 30px; padding-top: 2px;">
              <p-button type="primary" @click="searchQuery" icon="search">查询</p-button>
              <p-button type="primary" @click="searchReset" icon="reload" style="margin: 0 8px">重置</p-button>
            </div>
          </p-col>
        </p-row>
      </p-form>
    </div>

    <!--高级查询-->
    <div class="ant-alert ant-alert-info" style="margin-bottom: 16px; text-align: right">
      <p-popover title="自定义列" trigger="click" placement="leftBottom">
        <template slot="content">
          <p-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
            <p-row>
              <template v-for="(item,index) in defColumns">
                <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                    <p-col :span="12"><p-checkbox :value="item.dataIndex">{{ item.title }}</p-checkbox></p-col>
                </template>
              </template>
            </p-row>
          </p-checkbox-group>
        </template>
        <a><p-icon type="setting" />自定义列</a>
      </p-popover>
    </div>

    <p-table
      :columns="columns"
      :dataSource="dataSource"
      :pagination="false"
      :row-key="getRowKey"
      :scroll="{x: 1160, y: 400}"
      class="sopmaterial-table"
      ref="table"
      size="middle"
      bordered
    >
      <template slot="action" slot-scope="text, record, index">
        <template v-if="record.workstationCode">
          <a @click="editItem(record, index)">编辑</a>
          <p-divider type="vertical" />
          <p-popconfirm title="确定要删除吗?" @confirm="deleteItem(record, index)">
            <a>删除</a>
          </p-popconfirm>
        </template>
        <template v-else-if="record.remainQuantitySelf">
          <a @click="editItem(record, index)">分配</a>
        </template>
      </template>
    </p-table>

    <component
      :is="view"
      v-model="viewVisible"
      :options="options"
      :items="stations"
      @callback="callback"
    />
  </p-modal>
</template>

<script>
import Vue from 'vue'

export default {
  components: {
    Distribute: () => import('./distribute')
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object
    }
  },
  data() {
    return {
      visible: false,
      columns: [],
      settingColumns: [],
      defColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 40,
          align: 'center',
          fixed: 'left',
          customRender(text, record) {
            if (record.index !== undefined) {
              return record.index + 1
            }
            return ''
          }
        },
        {
          title: '物料编码',
          align: 'center',
          // fixed: 'left',
          width: 90,
          ellipsis: true,
          dataIndex: 'mcode',
        },
        {
          title: '物料名称',
          align: 'center',
          // fixed: 'left',
          // width: 90,
          ellipsis: true,
          dataIndex: 'mname',
        },
        {
          title: '物料描述',
          align: 'center',
          width: 90,
          ellipsis: true,
          dataIndex: 'mexplain'
        },
        {
          title: '单位',
          align: 'center',
          width: 60,
          dataIndex: 'unit'
        },
        {
          title: '层级',
          align: 'center',
          width: 60,
          dataIndex: 'bomLevel'
        },
        {
          title: '替代组',
          align: 'center',
          width: 60,
          dataIndex: 'bomGroup'
        },
        {
          title: '总数量',
          align: 'center',
          width: 60,
          dataIndex: 'allQuantitySelf',
        },
        {
          title: '可分配数量',
          align: 'center',
          width: 90,
          dataIndex: 'remainQuantitySelf',
        },
        {
          title: '是否关键物料',
          align: 'center',
          width: 90,
          dataIndex: 'maintenanceKey',
          customRender(text) {
            let val
            switch (text.toString()) {
              case '1':
                val = '是'
                break
              case '2':
                val = '否'
                break
            }

            return val
          }
        },
        {
          title: 'SAP管控类型',
          align: 'center',
          width: 90,
          dataIndex: 'maintenanceSap',
          customRender(text) {
            let val
            switch (text) {
              case 1:
                val = 'SN管控'
                break
              case 2:
                val = 'PN管控'
                break
            }

            return val
          }
        },
        {
          title: '工站编码',
          align: 'center',
          width: 90,
          dataIndex: 'workstationCode',
        },
        {
          title: '工站名称',
          align: 'center',
          width: 90,
          ellipsis: true,
          dataIndex: 'workstationName'
        },
        {
          title: '工站所需数量',
          align: 'center',
          width: 90,
          dataIndex: 'stationsRequired',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 90,
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      model: {},
      params: {
        mcode: '',
        workstationCode: '',
        maintenanceSap: ''
      },
      dataSource: [],
      stations: [],
      viewVisible: false,
      view: '',
      options: null
    }
  },
  watch: {
    value() {
      this.initValue()
    },
    visible(val) {
      if (!val) {
        this.$emit('input', val)
      }
    }
  },
  created() {
    this.initColumns()
  },
  mounted() {
    this.initValue()
  },
  methods: {
    initValue() {
      this.visible = this.value
      if (this.value) {
        if (this.options) {
          const { form, data, treeData } = this.options
          const dataSource = []
          this.model = form || {}
          this.dataSource = data || []
          this.stations = treeData || []
        } else {
          this.model = {}
          this.dataSource = []
          this.stations = []
        }
      }
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = "sopMaterial:colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        })
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        })
        this.columns = cols;
      }
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = "sopMaterial:colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols;
    },
    searchReset() {
      this.params.mcode = ''
      this.params.workstationCode = ''
      this.params.maintenanceSap = ''
    },
    onOk() {
      this.visible = false
      this.$emit('callback', this.dataSource, 'sopMaterial')
    },
    onCancel() {
      this.dataSource = []
    },
    deleteItem(record, index) {
      record.parent.remainQuantitySelf += record.stationsRequired
      this.dataSource.splice(index, 1)
    },
    editItem(record, index) {
      this.currentIndex = index
      const { mcode, mname, remainQuantitySelf, workstationCode, workstationName, stationsRequired, maintenanceKey } = record
      this.options = {
        mcode,
        mname,
        remainQuantitySelf: record.parent ? record.parent.remainQuantitySelf + stationsRequired : remainQuantitySelf,
        workstationCode,
        workstationName,
        stationsRequired,
        maintenanceKey
      }
      this.view = 'distribute'
      this.viewVisible = true
    },
    callback(data) {
      let item = this.dataSource[this.currentIndex]
      let index = -1
      /**
       * 如果是编辑已经分配的，就比较简单，只需要把数据填充回去
       * 如果新分配的，先看看是否存在相同工站的，有的话，把数据直接填充
       * 否则得找到物料及最后一条分配记录，再把数据插入数组中
       */
      if (!item.parent) {
        index = this.dataSource.findIndex(item => item.mcode === data.mcode && item.workstationCode === data.workstationCode)
        if (index !== -1) {
          item = this.dataSource[index]
        } else {
          item = null
        }
      }
      if (item && item.parent) {
        item.parent.remainQuantitySelf = item.parent.remainQuantitySelf + item.stationsRequired - data.stationsRequired
      } else {
        const parentIndex = this.dataSource.findIndex(item => item.mcode === data.mcode && !item.workstationCode)
        const nearlyIndex = this.dataSource.findIndex((item, index) => index >= parentIndex && item.mcode !== data.mcode)
        const parent = this.dataSource[parentIndex]
        parent.remainQuantitySelf = parent.remainQuantitySelf - data.stationsRequired
        item = Object.assign({}, parent)
        item.remainQuantitySelf = null
        item.allQuantitySelf = null
        item.parent = parent
        delete item.index
        if (nearlyIndex !== -1) {
          this.dataSource.splice(nearlyIndex, 0, item)
        } else {
          this.dataSource.push(item)
        }
      }
      if (item) {
        item.stationsRequired = data.stationsRequired
        item.workstationCode = data.workstationCode
        item.workstationName = data.workstationName
        item.maintenanceKey = data.maintenanceKey
      }
    },
    getRowKey(item) {
      return item.id + (item.workstationCode ? '-' + item.workstationCode : '')
    }
  }
}
</script>

<style lang="less">
.sopmaterial-table {
  .poros-table-row-indent + .poros-table-row-expand-icon {
    margin-right: 0;
  }
}
</style>